﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interop;
using P2PChat.Data;
using P2PChat.Client.Data;
using System.Xml.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace P2PChat.Client.UI
{
    /// <summary>
    /// WinChat.xaml 的交互逻辑
    /// </summary>
    public partial class WinChat : Window
    {
        public WinChat()
        {
            InitializeComponent();
        }

        //public SessionType type = SessionType.Single;

        /// <summary>
        /// 1 为系统Session
        /// 0 为空Session
        /// </summary>
        public int SessionNumber { get; set; }

        public UIElementCollection MemberPanelChildren
        {
            get
            {
                return panel_Members.Children;
            }
        }

        public UIElementCollection MessagePanelChildren
        {
            get
            {
                return panel_Messages.Children;
            }
        }

        public StackPanel MessagePanel
        {
            get
            {
                return panel_Messages;
            }
        }

        private void window_Load(object sender, RoutedEventArgs e)
        {
            txt_Input.Clear();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }

        public void InsertUI(UIElement ui)
        {
            panel_Messages.Children.Add(ui);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (txt_Input.Text.Trim() != "")
            {
                System.Threading.Thread thread_SendTextMessage = new System.Threading.Thread(threadMain_SendTextMessage);
                thread_SendTextMessage.Start();
            }
        }

        private void threadMain_SendTextMessage() {
            string inputedText = null;
            this.Dispatcher.Invoke(new Action(() =>
            {
                inputedText = txt_Input.Text;
            }));

            try
            {
                // ### 向Session中添加数据 ###
                // /MessageList/*
                if (ChatSession.Sessions[SessionNumber].Element("MessageList") == null)
                {
                    ChatSession.Sessions[SessionNumber].Add(new XElement("MessageList"));
                }
                ChatSession.Sessions[SessionNumber].Element("MessageList").Add(
                    new XElement("Text", new XAttribute("SenderID", PersonalInfo.UserId.ToString()),
                        new XAttribute("Index", ChatSession.Sessions[SessionNumber].Element("MessageList").Elements().Count() + 1),
                        inputedText));


                // ### 刷新窗口 ###
                Dispatcher.Invoke(new Action(() => {
                    TextBlock lb_MessageSend = new TextBlock() {
                        Text = string.Format(@"{0}: {1}", PersonalInfo.Nickname ,inputedText),
                        TextWrapping = TextWrapping.Wrap,
                    };
                    panel_Messages.Children.Add(lb_MessageSend);
                }));


                // ### 发送消息 ###
                foreach (XElement memberXMl in ChatSession.Sessions[SessionNumber].Element("MemberList").Elements("Member"))
                {
                    using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient()) {
                        client.Connect(memberXMl.Element("IPEndPoint").Element("IPAddress").Value,
                            int.Parse(memberXMl.Element("IPEndPoint").Element("Port").Value));
                        
                        if (client.Connected) {
                            MemoryStream ms = new MemoryStream();
                            BinaryFormatter bf = new BinaryFormatter();
                            bf.Serialize(ms, new NetPacket() {
                                Tag = PacketTag.Message,
                                Content = new P2PChat.Data.Packets.TextMessagePacket() {
                                    SenderId = PersonalInfo.UserId,
                                    SenderSession = SessionNumber,
                                    ReceiverSession = int.Parse(memberXMl.Element("SessionId").Value),
                                    Message = inputedText,
                                    ListeningPort = GlobalConfig.ListeningPort,
                                },
                            });

                            client.Client.Send(ms.GetBuffer());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    Label lb_ErrorMessage = new Label()
                    {
                        Content = "侦测到异常: " + ex.Message,
                    };
                    panel_Messages.Children.Add(lb_ErrorMessage);
                }));
            }
        }
    }
}
